local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog = require "filelog"
local timetool = require "timetool"

require "imenum"

local NoticeMgr = {
	CMD = {},
    notice_data = {},  ---通知gate服务上玩家的缓存
}

function NoticeMgr.CMD.push_notice(send_to_rid, newmessage_num)
    local send_cache = NoticeMgr.notice_data[send_to_rid]
    if not send_cache then
        NoticeMgr.notice_data[send_to_rid] = { newmessage_num = 0 }
        send_cache = NoticeMgr.notice_data[send_to_rid]
    end
    if newmessage_num > 0 then
        send_cache.newmessage_num = send_cache.newmessage_num + newmessage_num
    end
end

function NoticeMgr:notice_gate(rid, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
        retcode = tonumber(message.retcode)
        retstr = message.retstr or ""
        msgbody = message.msgbody or { }
    else
        msgbody = message
    end
    local rids = { }
    table.insert(rids,rid)
    local status = skynet.pcall(cluster.send,"gatenode", ".router", "notify", rids, "im."..msgname, message, retcode, retstr)
end


function NoticeMgr:notice_all()
    for send_to_rid, send_cache in pairs(NoticeMgr.notice_data) do
        if send_cache.newmessage_num > 0 then
            local noticemsg = {
                newmessage_num = send_cache.newmessage_num,
            }
            NoticeMgr:notice_gate(send_to_rid, "messagegateN", noticemsg)
        end
    end
    NoticeMgr.notice_data = {}
end

function NoticeMgr:start()
    skynet.fork(function() 
        while true do
            NoticeMgr:notice_all()
            skynet.sleep(1*100)
        end
    end)
end



skynet.start(function() 
	skynet.dispatch("lua",function(session, source, cmd, ...)
        local f = NoticeMgr.CMD[cmd]
        if f then
            skynet.retpack(f(...))
        else
            skynet.retpack()
        end
    end)
    NoticeMgr:start() 
end)